package app.listener;

import javax.servlet.ServletContext;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ServletContextAware;

import app.thread.CollectionDataThread;
import app.thread.ScanLoginThread;
import app.util.ThreadUtil;

/**
 * springListener 加载完成后,执行
 * @author zoe
 *
 */
@Service
public class StartupListener implements ApplicationContextAware, ServletContextAware, InitializingBean, ApplicationListener<ContextRefreshedEvent> {

	protected Logger logger = LogManager.getLogger(Object.class);

	@Override
	public void setApplicationContext(ApplicationContext ctx) throws BeansException {
		logger.info("1 => StartupListener.setApplicationContext");
	}

	@Override
	public void setServletContext(ServletContext context) {
		logger.info("2 => StartupListener.setServletContext");
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		logger.info("3 => StartupListener.afterPropertiesSet");
	}

	@Override
	public void onApplicationEvent(ContextRefreshedEvent evt) {
		logger.info("4.1 => MyApplicationListener.onApplicationEvent");
		if (evt.getApplicationContext().getParent() == null) {
			logger.info("4.2 => MyApplicationListener.onApplicationEvent");
			logger.info("===============启动自定义监听===============");
			
			CollectionDataThread target = (CollectionDataThread)evt.getApplicationContext().getBean("collectionDataThread");
			ThreadUtil.newCachedThreadPool.execute(target);
			ThreadUtil.setRunningThread(CollectionDataThread.class.getName(), target);
			logger.info("===============结束自定义监听===============");
		}
	}

}

//@Service
//public class InitAfterSpringListener implements InitializingBean{
//
//	@Resource
//	private ActiveOnlineThread activeOnlineThread;
//	
//	@Override
//	public void afterPropertiesSet() throws Exception {
//		ThreadUtil.newCachedThreadPool.execute(activeOnlineThread);
//		System.out.println("启动");
//	}
//	
//}
//public class InitAfterSpringListener implements ApplicationListener<ContextRefreshedEvent> {
//
//	@Override
//	public void onApplicationEvent(ContextRefreshedEvent event) {
//		if(event.getApplicationContext().getParent() == null){//root application context 没有parent，他就是老大.
//			ActiveOnlineThread bean = (ActiveOnlineThread)event.getApplicationContext().getBean("activeOnlineThread");
//			ThreadUtil.newCachedThreadPool.execute(bean);
//			System.out.println("启动");
//		}
//	}
//}